﻿using MediatR;
using SmartMedicalCare.API.Read.Applications.Commands.科室;
using SmartMedicalCare.Domain;
using SmartMedicalCare.ErronCode;
using SmartMedicalCare.Infrastructure.Implaction;
using SmartMedicalCare.Infrastructure.Migrations;
using System.Xml.Linq;

namespace SmartMedicalCare.API.Read.Applications.CommandHandlers.科室
{
    public class QueryDepartmentCommandHandler : IRequestHandler<QueryDepartmentCommand, APIResult<APIPaging<DepartmentModel>>>
    {
        private readonly IBaseRespository<DepartmentModel> depRep;

        public QueryDepartmentCommandHandler(IBaseRespository<DepartmentModel> depRep)
        {
            this.depRep = depRep;
        }

        public Task<APIResult<APIPaging<DepartmentModel>>> Handle(QueryDepartmentCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<DepartmentModel>> result=new APIResult<APIPaging<DepartmentModel>>();
            result.code=ResultCode.显示成功;
            result.Message=ResultCode.显示成功.ToString();

            var res = from a in depRep.GetAll()
                      where !a.IsDeleted
                      select new DepartmentModel
                      {
                          DepartmentId=a.DepartmentId,
                          HospitalId=a.HospitalId,
                          Css=a.Css,
                          Name=a.Name,
                          Intro=a.Intro,

                          Status=a.Status,

                          CreateTime = a.CreateTime ,
                          IsDeleted= a.IsDeleted    ,
                          CreateName=a.CreateName,
                      };
            //总条数
            var totalcount=res.Count();
            //总页数
            var totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.Pagsize);
            //排序
            res = res.OrderByDescending(x => x.DepartmentId).Skip((request.Pagindex - 1) * request.Pagsize).Take(request.Pagsize);

            APIPaging < DepartmentModel > paging=new APIPaging<DepartmentModel>();
            paging.totalCount = totalcount;
            paging.totalPage = totalpage;
            paging.Fdata=res.ToList ();
            result.Data = paging;
            return Task.FromResult(result);
        }
    }
}
